#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


from django.template import Library
from collections import OrderedDict

from django.conf import settings
from rbac.templatetags import urls
from rbac.models import User

register = Library()


# @register.inclusion_tag('first_menu.html')
# def first_menu(request):
#     menu_list = request.session[settings.MENU_SESSION_KEY]
#     print(menu_list)
#     for i in menu_list:
#         print(i)
#     return {'menu_list': menu_list}


@register.inclusion_tag('second_menu.html')
def second_menu(request):
    menu_dict = request.session.get(settings.MENU_SESSION_KEY, None)
    if menu_dict:
        key_list = sorted(menu_dict)
        ordered_dict = OrderedDict()
        for key in key_list:
            val = menu_dict[key]
            for per in val['children']:
                if per['id'] == request.current_selected_permission:
                    per['class'] = 'active'
                    val['class'] = 'active'
            if len(val['children']) == 1:
                one_url = val['children'][0]['url']
                val['url'] = one_url
                val['children'] = []
            ordered_dict[key] = val
        return {'menu_dict': ordered_dict}
    else:
        return {'menu_dict': None}


@register.inclusion_tag('breadcrumb.html')
def breadcrumb(request):
    flag = False
    if hasattr(request, 'breadcrumb'):
        if request.breadcrumb:
            flag = True
            title = request.breadcrumb[-1]['title']

    if not flag:
        request.breadcrumb = []
        title = '初始化'
    return {'record_list': request.breadcrumb, 'title': title}


@register.filter
def has_permission(request, name):
    """
    判断是否有权限
    :param request:
    :param name:
    :return:
    """
    permission_dict = request.session.get(settings.PERMISSION_SESSION_KEY, None)
    if permission_dict:
        if name in permission_dict:
            return True


@register.simple_tag
def title(request, *args, **kwargs):
    flag = False
    if hasattr(request, 'breadcrumb'):
        if request.breadcrumb:
            flag = True
            title = request.breadcrumb[-1]['title']

    if not flag:
        title = '初始化'
    return title


@register.simple_tag
def fullname(request):
    id = request.session.get('ID', None)
    if id:
        return User.objects.filter(pk=id).first().fullname
    else:
        return "NULL"


@register.simple_tag
def memory_url(request, name, *args, **kwargs):
    """
    生成带有原搜索条件的URL，替代了模板中的url
    :param request:
    :param name:
    :return:
    """
    return urls.memory_url(request, name, *args, **kwargs)
